package com.franzliszt.maillist.atcivity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.franzliszt.maillist.R;
import com.franzliszt.maillist.adapter.AllManAdapter;
import com.franzliszt.maillist.adapter.ContactsItemDecoration;
import com.franzliszt.maillist.customview.SideBar;
import com.franzliszt.maillist.sql.Dao;
import com.franzliszt.maillist.sql.News;
import com.franzliszt.maillist.util.ContactsInfo;
import com.franzliszt.maillist.util.Emergency;
import com.franzliszt.maillist.util.KillProcess;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ContactsActivity extends AppCompatActivity {
    private RecyclerView AllMan;
    private AllManAdapter Adapter;
    private SideBar SideBar;
    private TextView TipsText;
    private List<ContactsInfo> contactsInfoList = new ArrayList<>();
    private TextView addContacts;
    private Dao dao;
    private List<News> newsList = new ArrayList<>();
    private KillProcess killProcess;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE );
            getWindow().setStatusBarColor( Color.TRANSPARENT );
        }
        setContentView(R.layout.activity_contacts);
        InitView();
        AddEmergency();
        InitContacts();
        InitRecycler();
        Listener();
        Permission();

    }
    private void  InitView(){
        AllMan = findViewById(R.id.AllMan);
        SideBar = findViewById(R.id.ScrollBar);
        TipsText = findViewById(R.id.TipsText);
        addContacts = findViewById(R.id.AddContacts);
        addContacts.setText("添加");
        dao = new Dao(ContactsActivity.this);

        killProcess = KillProcess.getInstance();
        killProcess.PushActivity(ContactsActivity.this);
        //dao.DeleteAll();
    }
    private void InitRecycler(){
        final LinearLayoutManager manager = new LinearLayoutManager(ContactsActivity.this);
        AllMan.setLayoutManager(manager);
        Adapter = new AllManAdapter(contactsInfoList);
        AllMan.setAdapter(Adapter);
        AllMan.addItemDecoration(new ContactsItemDecoration(contactsInfoList));

        SideBar.setOnTouchLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                int position = Adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position, 0);
                }
            }
        });
        SideBar.setOnTextPositionChangedListener(new SideBar.OnTextPositionChangedListener() {
            @Override
            public void onTextPositionChanged(String c, int y) {
                TipsText.setVisibility(View.VISIBLE);
                int sideBarY = SideBar.getTop();
                int topMargin = sideBarY + y - TipsText.getHeight() / 2;
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) TipsText.getLayoutParams();
                lp.topMargin = topMargin;
                TipsText.setLayoutParams(lp);
                TipsText.setText(c);
            }

            @Override
            public void onActionUp() {
                TipsText.setVisibility(View.INVISIBLE);
            }
        });

        Adapter.Freshen();
    }
    //申请拨号权限
    private void Permission(){
        if (ActivityCompat.checkSelfPermission(ContactsActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ContactsActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
        }
    }
    private void Listener(){
        Adapter.setOnclick(new AllManAdapter.OnClick() {
            @Override
            public void OnClickListener(View view, int Position) {
                Intent intent = new Intent(ContactsActivity.this,DetailsActivity.class);
                String Phone = contactsInfoList.get(Position).getCityID();
                intent.putExtra("PhoneNumber",Phone);
                startActivity(intent);
            }
        });
    }
    private void InitContacts(){
        newsList = dao.QueryAll();
        RemoveAll();
        String curGroup = "0";
        ArrayList<String> indexList = new ArrayList<>();
        if (newsList != null){
            for (int i = 0; i <newsList.size() ; i++) {
                ContactsInfo info = new ContactsInfo(newsList.get(i).getLastName()+newsList.get(i).getFirstName(),newsList.get(i).getPinYin(),newsList.get(i).getPhoneNumber(),false,false);
                if (!info.getGroup().equals(curGroup)) {
                    // group 信息与保存的不一致, 那么就是该 group 的第一个
                    info.setIsFirstInGroup(true);
                    // 同时将该 group 信息添加到索引中
                    indexList.add(info.getGroup());
                    // 它的上一个城市就是上一个 group 的最后一个
                    if (i > 0) {
                        contactsInfoList.get(contactsInfoList.size() - 1).setIsLastInGroup(true);
                    }
                    curGroup = info.getGroup();
                }
                contactsInfoList.add(info);
            }
        }
    }
    private void RemoveAll(){
        if (contactsInfoList != null) {
            for (int i = 0; i < contactsInfoList.size(); i++) {
                contactsInfoList.remove(i);
            }
        }
    }
//    添加紧急报警电话
    private void AddEmergency(){
        try {
            newsList = dao.QueryAll();
        }catch (NullPointerException e){
            for (int i = 0; i < 4; i++) {
                dao.Insert(new News(Emergency.PoliceTel[i][0],Emergency.PoliceTel[i][1],Emergency.PoliceTel[i][2],Emergency.PoliceTel[i][3],"-","-","-"));
            }
        }
    }
    public void OtherThings(View view){
        Intent intent = new Intent(ContactsActivity.this,IncreaseActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putSerializable("list",(Serializable) contactsInfoList);
//        intent.putExtras(bundle);
        startActivity(intent);
    }
    public void Exit(View view){
       killProcess.finishAll();
    }
}

